<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇游戏</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Arial', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            color: #333;
        }

        .game-container {
            text-align: center;
            background: white;
            padding: 20px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
        }

        .score-board {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
            font-size: 18px;
            font-weight: bold;
        }

        .score-item {
            background: #f0f0f0;
            padding: 10px 20px;
            border-radius: 10px;
            margin: 0 10px;
        }

        #gameCanvas {
            border: 3px solid #333;
            border-radius: 10px;
            background: #2c3e50;
            display: block;
            margin: 0 auto;
        }

        .game-info {
            margin-top: 20px;
            font-size: 16px;
            color: #666;
        }

        .controls {
            margin-top: 15px;
            font-size: 14px;
            color: #888;
        }

        .game-over {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 30px;
            border-radius: 15px;
            text-align: center;
            display: none;
        }

        .restart-btn {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 10px 20px;
            font-size: 16px;
            border-radius: 5px;
            cursor: pointer;
            margin-top: 10px;
        }

        .restart-btn:hover {
            background: #45a049;
        }
    </style>
</head>
<body>
    <div class="game-container">
        <h1 style="margin-bottom: 20px; color: #333;">贪吃蛇游戏</h1>
        
        <div class="score-board">
            <div class="score-item">
                <span>当前分数: </span>
                <span id="currentScore">0</span>
            </div>
            <div class="score-item">
                <span>最高分数: </span>
                <span id="highScore">0</span>
            </div>
        </div>

        <canvas id="gameCanvas" width="400" height="400"></canvas>
        
        <div class="game-info">
            <p>使用方向键控制蛇的移动</p>
            <div class="controls">
                <p>↑ ↓ ← → 方向键移动</p>
            </div>
        </div>

        <div class="game-over" id="gameOver">
            <h2>游戏结束!</h2>
            <p>最终得分: <span id="finalScore">0</span></p>
            <button class="restart-btn" onclick="restartGame()">重新开始</button>
        </div>
    </div>

    <script>
        // 游戏配置
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const currentScoreEl = document.getElementById('currentScore');
        const highScoreEl = document.getElementById('highScore');
        const gameOverEl = document.getElementById('gameOver');
        const finalScoreEl = document.getElementById('finalScore');

        // 游戏参数
        const GRID_SIZE = 20;
        const GRID_WIDTH = canvas.width / GRID_SIZE;
        const GRID_HEIGHT = canvas.height / GRID_SIZE;

        // 游戏状态
        let snake = [];
        let food = {};
        let direction = 'right';
        let nextDirection = 'right';
        let score = 0;
        let highScore = localStorage.getItem('snakeHighScore') || 0;
        let gameRunning = false;
        let gameLoop = null;

        // 初始化最高分显示
        highScoreEl.textContent = highScore;

        // 初始化游戏
        function initGame() {
            // 初始化蛇
            snake = [
                {x: 5, y: 10},
                {x: 4, y: 10},
                {x: 3, y: 10}
            ];
            
            // 初始化食物
            generateFood();
            
            // 重置游戏状态
            direction = 'right';
            nextDirection = 'right';
            score = 0;
            currentScoreEl.textContent = score;
            gameRunning = true;
            
            // 隐藏游戏结束界面
            gameOverEl.style.display = 'none';
            
            // 开始游戏循环
            if (gameLoop) clearInterval(gameLoop);
            gameLoop = setInterval(gameStep, 150);
        }

        // 生成食物
        function generateFood() {
            let newFood;
            do {
                newFood = {
                    x: Math.floor(Math.random() * GRID_WIDTH),
                    y: Math.floor(Math.random() * GRID_HEIGHT)
                };
            } while (snake.some(segment => segment.x === newFood.x && segment.y === newFood.y));
            
            food = newFood;
        }

        // 游戏主循环
        function gameStep() {
            if (!gameRunning) return;
            
            // 更新方向
            direction = nextDirection;
            
            // 计算新的蛇头位置
            const head = {...snake[0]};
            switch (direction) {
                case 'up': head.y--; break;
                case 'down': head.y++; break;
                case 'left': head.x--; break;
                case 'right': head.x++; break;
            }
            
            // 检查碰撞
            if (checkCollision(head)) {
                gameOver();
                return;
            }
            
            // 添加新的蛇头
            snake.unshift(head);
            
            // 检查是否吃到食物
            if (head.x === food.x && head.y === food.y) {
                score++;
                currentScoreEl.textContent = score;
                generateFood();
                
                // 更新最高分
                if (score > highScore) {
                    highScore = score;
                    highScoreEl.textContent = highScore;
                    localStorage.setItem('snakeHighScore', highScore);
                }
            } else {
                // 如果没有吃到食物，移除蛇尾
                snake.pop();
            }
            
            // 绘制游戏
            draw();
        }

        // 检查碰撞
        function checkCollision(head) {
            // 检查墙壁碰撞
            if (head.x < 0 || head.x >= GRID_WIDTH || head.y < 0 || head.y >= GRID_HEIGHT) {
                return true;
            }
            
            // 检查自身碰撞
            return snake.some(segment => segment.x === head.x && segment.y === head.y);
        }

        // 绘制游戏
        function draw() {
            // 清空画布
            ctx.fillStyle = '#2c3e50';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // 绘制蛇
            ctx.fillStyle = '#4CAF50';
            snake.forEach((segment, index) => {
                if (index === 0) {
                    // 蛇头
                    ctx.fillStyle = '#45a049';
                } else {
                    // 蛇身
                    ctx.fillStyle = '#4CAF50';
                }
                ctx.fillRect(segment.x * GRID_SIZE, segment.y * GRID_SIZE, GRID_SIZE - 2, GRID_SIZE - 2);
            });
            
            // 绘制食物
            ctx.fillStyle = '#ff6b6b';
            ctx.beginPath();
            ctx.arc(
                food.x * GRID_SIZE + GRID_SIZE/2,
                food.y * GRID_SIZE + GRID_SIZE/2,
                GRID_SIZE/2 - 2,
                0,
                2 * Math.PI
            );
            ctx.fill();
        }

        // 游戏结束
        function gameOver() {
            gameRunning = false;
            clearInterval(gameLoop);
            finalScoreEl.textContent = score;
            gameOverEl.style.display = 'block';
        }

        // 重新开始游戏
        function restartGame() {
            initGame();
        }

        // 键盘控制
        document.addEventListener('keydown', (e) => {
            if (!gameRunning) return;
            
            switch (e.key) {
                case 'ArrowUp':
                    if (direction !== 'down') nextDirection = 'up';
                    break;
                case 'ArrowDown':
                    if (direction !== 'up') nextDirection = 'down';
                    break;
                case 'ArrowLeft':
                    if (direction !== 'right') nextDirection = 'left';
                    break;
                case 'ArrowRight':
                    if (direction !== 'left') nextDirection = 'right';
                    break;
            }
            
            // 防止方向键滚动页面
            e.preventDefault();
        });

        // 初始化游戏
        initGame();
    </script>
</body>
</html>